package com.yanxu;

/**
 * @author 折戟沉沙铁未销
 * @version V1.0
 * @date 2024/11/11-2024
 * @Description: 交替打印奇数偶数
 */
public class WaitNotifyPrintOddEvenSyn {
    public static Object obj_lock = new Object();
    public static Integer number = 0;

    public static void main(String[] args) throws InterruptedException {
        PrintData printData = new PrintData(obj_lock, number);
        Thread thread1 = new Thread(printData,"线程1");
        Thread thread2 = new Thread(printData,"线程2");

        //这种方式有错误
        /*Thread thread1 = new Thread(new PrintData(obj_lock, number),"线程1");
        Thread thread2 = new Thread(new PrintData(obj_lock, number),"线程2");
        thread1.start();
        thread2.start();*/
    }
}

class PrintData implements Runnable {
    public Object object_lock;
    public Integer number;

    public PrintData(Object object_lock, Integer number) {
        this.object_lock = object_lock;
        this.number = number;
    }

    public void run() {
        while (number <= 100) {
            synchronized (object_lock) {
                System.out.println(Thread.currentThread().getName() + " : " + number);
                number++;
                //唤醒其他线程
                object_lock.notify();
                try {
                    if (number <= 100) {
                        //自己进入休眠的状态
                        object_lock.wait();
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}